package cn.jimmie.learn.viewArt.captcha;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.jimmie.learn.viewArt.R;
import cn.jimmie.learn.viewArt.captcha.internal.OnSeekCaptchaVerifyListener;
import cn.jimmie.learn.viewArt.captcha.internal.SeekCaptchaView;
import cn.jimmie.learn.viewArt.captcha.internal.TextSeekBar;

/**
 * FUCTION :
 * Created by jimmie.qian on 2018/12/19.
 */
public class BlockCaptchaView extends RelativeLayout implements OnSeekCaptchaVerifyListener, View.OnClickListener, TextSeekBar.OnSeekBarChangeListener {

    private TextSeekBar mSeekBar;
    private SeekCaptchaView mSeekCaptchaView;
    private int mInitProgress;

    public BlockCaptchaView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BlockCaptchaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        View root = LayoutInflater.from(getContext()).inflate(R.layout.block_captcha_view, this);
        mSeekBar = root.findViewById(R.id.seek_captcha_bar);
        mSeekCaptchaView = root.findViewById(R.id.seek_captcha_view);
        root.findViewById(R.id.seek_captcha_refresh).setOnClickListener(this);

        mInitProgress = mSeekCaptchaView.getStartRegion();
        mSeekCaptchaView.setImageBitmap(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.m4399_ope_block_capthca_image));
        mSeekCaptchaView.setVerifyListener(this);
        mSeekCaptchaView.render();

        int max = mSeekCaptchaView.getMaxRegion();
        mSeekBar.setMax(max);
        mSeekBar.setListener(this);
        mSeekBar.setProgress(mInitProgress);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.seek_captcha_refresh) {
            mSeekCaptchaView.refreshBlock();
            mSeekBar.reset(mInitProgress);
        }
    }

    @Override
    public void onVerifySuccess() {
        Toast.makeText(getContext(), "验证成功!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onVerifyFailure() {
        mSeekCaptchaView.refreshBlock();
    }

    @Override
    public void onAnimationStart(boolean success) {
        if (!success) mSeekBar.resetWithAnimator(mInitProgress);
    }

    @Override
    public void onProgressChanged(int progress) {
        mSeekCaptchaView.updateOffset(progress);
    }

    @Override
    public void onStartTouch() {

    }

    @Override
    public void onStopTouch() {
        mSeekCaptchaView.verify();
    }
}
